package com.koalac.ironman.util;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.widget.Toast;
import cn.beecloud.BCPay;
import cn.beecloud.BCQuery;
import cn.beecloud.async.BCCallback;
import cn.beecloud.async.BCResult;
import cn.beecloud.entity.BCBillOrder;
import cn.beecloud.entity.BCPayResult;
import cn.beecloud.entity.BCQueryBillResult;
import cn.beecloud.entity.BCReqParams;

import com.foot.travel.otto.BusProvider;
import com.koalac.ironman.net.pojo.response.PayResultEvent;

public class BeeCloudUtil {
    
    private static final String TAG = "BeeCloudUtil";
    
    public static final String APP_ID = "3b1cfd11-cf8c-42ed-a9ec-c20bce2d71cf";
    public static final String APP_SECRET = "bfffae6d-9144-4be7-88ce-3dbd120f51ea";
    
    
    static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS", Locale.CHINA);
    Context mContext;
    
    public BeeCloudUtil(Context context) {
	 mContext = context;
    }
    
 /**
  * 支付宝支付
  * @param orderName 订单名
  * @param money 价格
  * @param orderNum 订单号
  */
    public   void alipay(String orderName,int money,String orderNum) {
	 Map<String, String> mapOptional = new HashMap<String, String>();
	 mapOptional.put("客户端", "安卓");
         mapOptional.put("consumptioncode", "consumptionCode");

         BCPay.getInstance(mContext).reqAliPaymentAsync(
        	 orderName,
        	 money,
        	 orderNum,
                 mapOptional,
                 bcCallback);
    }
    
     BCCallback bcCallback = new BCCallback() {
        @Override
        public void done(final BCResult bcResult) {
            final BCPayResult bcPayResult = (BCPayResult)bcResult;
            //此处关闭loading界面
          //根据你自己的需求处理支付结果
            //需要注意的是，此处如果涉及到UI的更新，请在UI主进程或者Handler操作
            ((Activity) mContext).runOnUiThread(new Runnable() {
                @Override
                public void run() {

                    String result = bcPayResult.getResult();

                    /*
                      注意！
                      所有支付渠道建议以服务端的状态金额为准，此处返回的RESULT_SUCCESS仅仅代表手机端支付成功
                    */
                    if (result.equals(BCPayResult.RESULT_SUCCESS)) {
                        Toast.makeText(mContext, "用户支付成功", Toast.LENGTH_LONG).show();
                        PayResultEvent payResultEvent = new PayResultEvent();
                        payResultEvent.setPaySuccess(true);
                        BusProvider.getBusInstance().post(payResultEvent);
                    } else if (result.equals(BCPayResult.RESULT_CANCEL))
                        Toast.makeText(mContext, "用户取消支付", Toast.LENGTH_LONG).show();
                    else if (result.equals(BCPayResult.RESULT_FAIL)) {
                        String toastMsg = "支付失败, 原因: " + bcPayResult.getErrCode() +
                                " # " + bcPayResult.getErrMsg() +
                                " # " + bcPayResult.getDetailInfo();
                        PayResultEvent payResultEvent = new PayResultEvent();
                        payResultEvent.setPaySuccess(false);
                        BusProvider.getBusInstance().post(payResultEvent);

                        /**
                         * 你发布的项目中不应该出现如下错误，此处由于支付宝政策原因，
                         * 不再提供支付宝支付的测试功能，所以给出提示说明
                         */
                        if (bcPayResult.getErrMsg().equals("PAY_FACTOR_NOT_SET") &&
                                bcPayResult.getDetailInfo().startsWith("支付宝参数")) {
                            toastMsg = "支付失败：由于支付宝政策原因，故不再提供支付宝支付的测试功能，给您带来的不便，敬请谅解";
                        }

                        /**
                         * 以下是正常流程，请按需处理失败信息
                         */

                        Toast.makeText(mContext, toastMsg, Toast.LENGTH_LONG).show();

                        if (bcPayResult.getErrMsg().equals(BCPayResult.FAIL_PLUGIN_NOT_INSTALLED) ||
                                bcPayResult.getErrMsg().equals(BCPayResult.FAIL_PLUGIN_NEED_UPGRADE)) {
                            //银联需要重新安装控件
                        }

                    } else if (result.equals(BCPayResult.RESULT_UNKNOWN)) {
                        //可能出现在支付宝8000返回状态
                        Toast.makeText(mContext, "订单状态未知", Toast.LENGTH_LONG).show();
                    } else {
                        Toast.makeText(mContext, "invalid return", Toast.LENGTH_LONG).show();
                    }

                    if (bcPayResult.getId() != null) {
                        //你可以把这个id存到你的订单中，下次直接通过这个id查询订单
                        Log.w(TAG, "bill id retrieved : " + bcPayResult.getId());

                        //根据ID查询
                        getBillInfoByID(bcPayResult.getId());
                    }
                }
            });
        }
    };
    
    
    void getBillInfoByID(String id) {

        BCQuery.getInstance().queryBillByIDAsync(id,
                new BCCallback() {
                    @Override
                    public void done(BCResult result) {
                        BCQueryBillResult billResult = (BCQueryBillResult) result;

                        Log.d(TAG, "------ response info ------");
                        Log.d(TAG, "------getResultCode------" + billResult.getResultCode());
                        Log.d(TAG, "------getResultMsg------" + billResult.getResultMsg());
                        Log.d(TAG, "------getErrDetail------" + billResult.getErrDetail());

                        Log.d(TAG, "------- bill info ------");
                        BCBillOrder billOrder = billResult.getBill();
                        Log.d(TAG, "订单号:" + billOrder.getBillNum());
                        Log.d(TAG, "订单金额, 单位为分:" + billOrder.getTotalFee());
                        Log.d(TAG, "渠道类型:" + BCReqParams.BCChannelTypes.getTranslatedChannelName(billOrder.getChannel()));
                        Log.d(TAG, "子渠道类型:" + BCReqParams.BCChannelTypes.getTranslatedChannelName(billOrder.getSubChannel()));

                        Log.d(TAG, "订单是否成功:" + billOrder.getPayResult());

                        if (billOrder.getPayResult())
                            Log.d(TAG, "渠道返回的交易号，未支付成功时，是不含该参数的:" + billOrder.getTradeNum());
                        else
                            Log.d(TAG, "订单是否被撤销，该参数仅在线下产品（例如二维码和扫码支付）有效:"
                                    + billOrder.getRevertResult());

                        Log.d(TAG, "订单创建时间:" + new Date(billOrder.getCreatedTime()));
                        Log.d(TAG, "扩展参数:" + billOrder.getOptional());
                        Log.w(TAG, "订单是否已经退款成功(用于后期查询): " + billOrder.getRefundResult());
                        Log.w(TAG, "渠道返回的详细信息，按需处理: " + billOrder.getMessageDetail());

                    }
                });
    }

}
